package com.beifu.manager.api.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.beifu.manager.api.domain.logon.MobileUserInfo;

public class MobilePrincipalFilter extends AccessControlFilter {
	
	private Logger Log = Logger.getLogger(this.getClass());
	
	private static final String MOBILE_LOGIN = "/login/api/login.api";
	private static final String NoLoginMes = "/login/noLoginMes.api";
	
	@Override
	protected boolean isAccessAllowed(ServletRequest arg0, ServletResponse arg1, Object arg2) throws Exception {
		Log.info("======MobilePrincipalFilter.isAccessAllowed......");
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Log.info("======MobilePrincipalFilter.onAccessDenied......");
		
		HttpServletRequest httpRequest  = (HttpServletRequest)request;
		String serverUrl = httpRequest.getRequestURI();
	
		Log.info("===【requestURI:】"+serverUrl+",【JsessionID:】"+httpRequest.getSession().getId()+"");
		
		if(MOBILE_LOGIN.equals(serverUrl)){//执行登录
			return true;
		}
		
		Subject subject = getSubject(request, response);
		if(subject.getPrincipal() == null){//没有登录
			Log.info("======MobilePrincipalFilter.没有登录......");
			 WebUtils.issueRedirect(request, response, NoLoginMes);
			 return false;
		}else{//已登录
			Object principal = subject.getPrincipal();
			if(!(principal instanceof MobileUserInfo)){
				Log.info("======MobilePrincipalFilter.未登录......");
				 WebUtils.issueRedirect(request, response, NoLoginMes);
				 return false;
			}
			Log.info("======MobilePrincipalFilter.已登录......");
		}
		return true;
	}
	
}
